import {
    registerUser,
    getCode,
    loginUser,
    reqUserInfo,
    loginOut
} from '@/api';
import {
    setToken,
    getToken,
    clearToken
} from '@/utils/token';

const actions = {
    //获取验证码
    async getCode({
        commit
    }, phone) {
        let result = await getCode(phone);
        commit('GET_CODE', result.data);
    },

    //注册用户
    async registerUser({
        commit,
        state
    }, {
        phone,
        password
    }) {
        let result = await registerUser({
            phone,
            password,
            code: state.code
        });

        if (result.code == 200)
            return 'ok';
        else return Promise.reject(result.message);
    },

    //用户登录
    async loginUser({
        state
    }, {
        phone,
        password
    }) {
        let result = await loginUser({
            phone,
            password
        });
        if (result.code == 200) {
            //把token存入到本地存储
            setToken(result.data.token);
            state.token = result.data.token;
            return 'ok';
        } else return Promise.reject(result.message)
    },

    //获取用户信息
    async getUserInfo({
        commit
    }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit('GET_USER_INFO', result.data);
        }
    },

    //用户退出
    async loginOut({
        state
    }) {
        let result = await loginOut();
        if (result.code == 200) {
            clearToken();
            state.userInfo = {};
            state.token = '';
        }
    }
}

const mutations = {
    //验证码
    GET_CODE(state, value) {
        state.code = value;
    },

    //用户信息
    GET_USER_INFO(state, value) {
        state.userInfo = value;
    }
}

const getters = {
    //返回验证码
    code() {
        return state.code;
    },

    //返回token
    token() {
        return state.token;
    },

    //返回用户信息
    userInfo() {
        return state.userInfo;
    }
}

const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}

export default {
    actions,
    mutations,
    getters,
    state
}